# -*- coding:utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class DynamicLineNumberLabel(QLabel):
    # 设置类属性，所有对象共享，不用重复创建
    __font = QFont()
    __font.setPixelSize(20)
    __font.setBold(True)
    __metrics = QFontMetrics(__font)
    def __init__(self, lineNumberWidthSignal, parent=None):
        super(DynamicLineNumberLabel, self).__init__(parent)
        self.setMaximumHeight(40)
        self.lineNumerSignal = lineNumberWidthSignal
        self.lineNumerSignal.connect(self.resizeLabelWidth)

    def setAutoLineNumber(self, lineNumber):
        self.setFont(DynamicLineNumberLabel.__font)
        self.setText(str(lineNumber))
        lineNumberLabelWidth = DynamicLineNumberLabel.__metrics.boundingRect(str(lineNumber)).size().width() * 1.4+10
        self.setMaximumWidth(lineNumberLabelWidth)
        return lineNumberLabelWidth

    def resizeLabelWidth(self, width):
        print("修改长度为", width)
        self.setMaximumWidth(width)


class FlowInfoPanel(QFrame):
    picPath = "./com/mat/rpa/views/workWindow/images/"
    def __init__(self, flowTitle, parent=None):
        super(FlowInfoPanel, self).__init__(parent)
        #设置总体布局
        self.entireLayout = QGridLayout()
        self.setLayout(self.entireLayout)
        self.entireLayout.setContentsMargins(0,5,5,5)
        self.entireLayout.setSpacing(0)
        #第一行
        self.imgLabel = QLabel()
        self.imgLabel.setPixmap(QPixmap(FlowInfoPanel.picPath+"openWebPage.png"))
        self.entireLayout.addWidget(self.imgLabel,0,0,1,1, alignment=Qt.AlignLeft)
        self.firstLineTitleLabel = QLabel()
        #字体为黑体。为了避免乱码不要在程序中写汉字，如果有汉字要使用unicode解码的方式。
        titleFontFamily = b'\\u9ed1\\u4f53'.decode("unicode_escape")
        self.firstLineTitleLabel.setStyleSheet("font-family:"+titleFontFamily+"; font-weight:bold;")
        self.firstLineTitleLabel.setText(flowTitle)
        self.entireLayout.addWidget(self.firstLineTitleLabel,0,1,1,1, alignment=Qt.AlignLeft)
        #第二行
        self.secondLineInfoLabel = QLabel()
        self.secondLineInfoLabel.setText("1111111111111111111")
        self.entireLayout.addWidget(self.secondLineInfoLabel,1,1,1,1, alignment=Qt.AlignLeft)
        self.entireLayout.setColumnStretch(0,2) #设置gridlayout拉伸时，第一列占拉伸比例1/100
        self.entireLayout.setColumnStretch(1,98)#而第二列占99/100

    def setSecondLineInfoLabelText(self, text):
        self.secondLineInfoLabel.setText(text)

    def enterEvent(self, event):
        self.setStyleSheet("background-color:#f8f9fa;")

    def leaveEvent(self, event):
        self.setStyleSheet("background-color:white;")

    # def mouseDoubleClickEvent(self, event):
    #     print("鼠标双击了flowPanel")

class IndentationLine(QWidget):
    def __init__(self, parent=None):
        super(IndentationLine, self).__init__(parent)
        self.entireLayout = QHBoxLayout()
        self.entireLayout.setContentsMargins(0,0,0,0)
        self.entireLayout.setSpacing(0)
        self.setLayout(self.entireLayout)
        self.line = QFrame()
        self.line.setFrameShape(QFrame.VLine)
        self.line.setFrameShadow(QFrame.Plain)
        self.line.setStyleSheet("color: #ccc;")
        self.entireLayout.addWidget(self.line)
        self.placeHolder = QLabel()
        self.placeHolder.setFixedWidth(10)
        self.entireLayout.addWidget(self.placeHolder)


class FlowStepWidget(QFrame):
    count = 0
    picPath = "./com/mat/rpa/views/workWindow/images/"
    def __init__(self, lineNumber, indentLevel, flowTitle, lineNumberWidthSignal, parent=None):
        super(FlowStepWidget, self).__init__(parent)
        self.parentPanel = parent
        self.setAcceptDrops(True)
        self.entireLayout = QHBoxLayout()
        self.setLayout(self.entireLayout)
        self.entireLayout.setContentsMargins(5,0,5,0)
        self.entireLayout.setSpacing(5)
        self.setObjectName("FlowStepWidget_"+str(FlowStepWidget.count))
        FlowStepWidget.count += 1
        #行号
        self.lineNumberWidth = 0
        self.lineNumberLabel = DynamicLineNumberLabel(lineNumberWidthSignal)
        self.lineNumberWidth = self.lineNumberLabel.setAutoLineNumber(lineNumber)
        self.entireLayout.addWidget(self.lineNumberLabel,1)
        #断点/错误提示
        self.breakPointOrErrorLabel = QLabel()
        self.breakPointOrErrorLabel.setPixmap(QPixmap(FlowStepWidget.picPath+"errorLine.png"))
        self.entireLayout.addWidget(self.breakPointOrErrorLabel)
        #代码伸缩图片
        self.codePucker = QPushButton()
        self.codePucker.setStyleSheet("border:none")
        self.codePucker.setIcon(QIcon(QPixmap(FlowStepWidget.picPath+"codeExpanded16.png")))
        self.codeFolded = False #默认代码展开，不收起
        self.codePucker.clicked.connect(self.handleCodePuckerClicked)
        self.codeEndFlowWidget = None #默认没有
        self.setCodePuckerVisible(False)
        self.entireLayout.addWidget(self.codePucker)

        #根据缩进层级插入多个分隔线
        for i in range(indentLevel):
            line = IndentationLine()
            self.entireLayout.addWidget(line)

        self.infoPanel = FlowInfoPanel(flowTitle)
        self.entireLayout.addWidget(self.infoPanel,9)

    def setErrorLabelVisible(self, visible):
        self.breakPointOrErrorLabel.setEnabled(visible)
        if visible:
            self.breakPointOrErrorLabel.setPixmap(QPixmap(FlowStepWidget.picPath+"errorLine.png"))
        else:
            self.breakPointOrErrorLabel.setPixmap(QPixmap(FlowStepWidget.picPath+"cover.png"))

    def setCodePuckerVisible(self, visibility):
        self.codePucker.setEnabled(visibility)
        if not visibility:
            self.codePucker.setIcon(QIcon(QPixmap(FlowStepWidget.picPath+"cover.png")))
        else:
            if self.codeFolded:
                self.codePucker.setIcon(QIcon(QPixmap(FlowStepWidget.picPath + "codeFolded16.png")))
            else:
                self.codePucker.setIcon(QIcon(QPixmap(FlowStepWidget.picPath + "codeExpanded16.png")))

    def setCodeEndFlowWidget(self, codeEndFlowWidget):
        self.codeEndFlowWidget = codeEndFlowWidget

    def handleCodePuckerClicked(self):
        if self.codeFolded:
            self.codeFolded = False
            self.codePucker.setIcon(QIcon(QPixmap(FlowStepWidget.picPath + "codeExpanded16.png")))
        else:
            self.codeFolded = True
            self.codePucker.setIcon(QIcon(QPixmap(FlowStepWidget.picPath + "codeFolded16.png")))

    def separateTreeNodeInfo(self, infoText):
        infoList = infoText.strip().split("|")
        return infoList

    def dragEnterEvent(self, e):
        if e.mimeData().hasText():
            inforList = self.separateTreeNodeInfo(e.mimeData().text())
            if inforList[0] == "leaf":
                self.infoPanel.setStyleSheet("FlowInfoPanel {border-top:2px solid #1890ff;}")
                e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        self.infoPanel.setStyleSheet("FlowStepWidget {border:none;}")
        currentIndex = self.parentPanel.innerWidgetLayout.indexOf(self)
        self.parentPanel.insertWidget(currentIndex, e)
        print("当前流程组件序号为", currentIndex)

    def dragLeaveEvent(self, event):
        self.infoPanel.setStyleSheet("FlowInfoPanel {border:none;}")

    def showBottomBorder(self):
        self.infoPanel.setStyleSheet("FlowInfoPanel {border-bottom:2px solid #1890ff;}")

    def hideBottomBorder(self):
        self.infoPanel.setStyleSheet("FlowInfoPanel {border:none;}")
